<template>
  <view class="search-details-page">
    <!-- 导航栏区域 -->
    <nav-bar @load="handleNavLoad">
      <view class="uni-easyinput-head">
        <uni-easyinput prefixIcon="search" v-model="searchContent" :inputBorder="false" @input="handleGetSearchSuggest"
          placeholder="请输入搜索内容" @confirm="handleSearch(searchContent)" @clear="handlePageInit">
        </uni-easyinput>
      </view>

    </nav-bar>

    <!-- 建议列表区域 -->
    <scroll-view scroll-y class="sugg-list-container" v-if="searchSuggeListShow"
      :style="{height:suggHeight+'px',top:navHeight+'px'}">
      <view class="sugg-item" v-for="(item,index) in SearchSuggeList" :key="index" @click="handleSearch(item)">
        <uni-icons type="search" :size="16" color="#ccc"></uni-icons>
        <view class="sugg-item-text">
          <text>{{item}}</text>
        </view>
      </view>
      <view class="sugg-tips">
        {{suggText}}
      </view>
    </scroll-view>

    <!-- 搜索历史区域 -->
    <view class="history-container" v-if="historyListShow&&historyList.length>0">

      <view class="history-title">
        <!-- 区域标题 -->
        <text class="title">搜索历史</text>
        <!-- 删除按钮 -->
        <view class="history-compile" v-if="historyEditStatus">
          <text class="history-empty" @click="handleCleanHistory">清空</text>
          <text>|</text>
          <text class="history-cancel" @click="historyCancel">取消</text>
        </view>
        <uni-icons v-else custom-prefix="iconfont" type="icon-delete" :size="16" @click="historyCancel">
        </uni-icons>
      </view>
      <!-- 历史词条 -->
      <view class="history-list-container">
        <view class="history-item" @longpress='handleRemoveSingleHistory(item)' v-for="(item, index) in historyList"
          :key="index" @click="handleHistoryClick(item)">
          <text class="text">{{item}}</text>
          <uni-icons class="remove-icon" custom-prefix="iconfont" type="icon-close" :size="12" v-if="historyEditStatus">
          </uni-icons>
        </view>
        <view class="history-item more-icon" :class="{'more-icon-expland':showAllHistoryListState}"
          v-if="historyListMoreStatus" @click="handleLoadMoreHistory">
          <uni-icons class="icon" type="bottom" :size="16"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 推荐与搜索结果区域 -->
    <view class="content-container">
      <!-- 选项卡 -->
      <view class="nav-container">
        <tabs-component :data="navList" :active="active" @change="handleNavChange"></tabs-component>
      </view>
      <view class="scroll-view-container" :style="{'height':contentHeight+'px'}">

        <!-- 文章列表 -->
        <scroll-view scroll-y :show-scrollbar="false" class="recommend-container" v-show="active === 0"
          @scrolltolower="handleLoadData">
          <view class="list-container">

            <!-- 文章搜索结果列表 -->
            <view v-for="item in ArticleListPage.list" :key='item.articleId' class="item">
              <article-block :data="item"></article-block>
            </view>


            <block v-if="searchContent&&ArticleListPage.reqStatus!=''">
              <view class="list-status-container" v-if="ArticleListPage.reqStatus=='loading'">
                <text>加载中...</text>
              </view>
              <view class="list-status-container" v-else-if="ArticleListPage.reqStatus=='done'">
                <text v-if="ArticleListPage.dataStatus=='no-more'">已全部加载</text>
                <text v-else-if="ArticleListPage.dataStatus=='empty'">没有找到你要搜索的内容...</text>
              </view>
            </block>

            <!-- 文章推荐列表-->
            <view class="recommend-article" v-if="searchContent&&ArticleListPage.dataStatus=='empty'||!searchContent">
              <block v-for="(item,index) in ArticleListPage.recommendList" :key='index'>
                <view class="item" @click="handleNavigateToArticleDetails(item)">
                  <view class="frame-item">{{index+1}}</view>
                  <view class="text-item">
                    <text>{{item.title}}</text>
                  </view>
                </view>
              </block>
            </view>

          </view>
        </scroll-view>

        <!-- 用户列表 -->
        <scroll-view scroll-y :show-scrollbar="false" class="user-container" v-show="active === 1"
          @scrolltolower="handleLoadData">
          <view class="list-container">
            <!-- 用户搜索结果列表 -->
            <view v-for="item in userListPage.list" :key='item.userId' class="item"
              :class="{'item-one':userListPage.list.length==1}">
              <user-item :userObj="item" @status-change="(value)=>{handleUserFansState(value,'list')}" :all="0"
                :userType='3'>
              </user-item>
            </view>

            <block v-if="searchContent&&userListPage.reqStatus!=''">
              <view class="list-status-container" v-if="userListPage.reqStatus=='loading'">
                <text>加载中...</text>
              </view>
              <view class="list-status-container" v-else-if="userListPage.reqStatus=='done'">
                <text v-if="userListPage.dataStatus=='no-more'">已全部加载</text>
                <text v-else-if="userListPage.dataStatus=='empty'">没有找到你要搜索的内容...</text>
              </view>
            </block>

            <!-- 用户推荐列表 -->
            <view class='recommend-user' v-if="searchContent&&userListPage.dataStatus=='empty'||!searchContent">
              <view v-for="item in userListPage.recommendList" :key='item.userId' class="item">
                <user-item :userObj="item" @status-change="(value)=>{handleUserFansState(value,'recommendList')}"
                  :all="0" :userType="2">
                </user-item>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

    </view>
  </view>
</template>
<script>
  import {
    getHotDiscloseApi,
    getHotUseApi,
    getSearchSuggestApi,
    getSearchDiscloseApi,
    getSearchUserApi
  } from '@/api/community/search.js'
  // 历史记录列表默认显示个数
  const HISTORY_LIST_SHOW_NUM = 6;
  export default {
    data() {
      return {
        windowHeight: 0,
        navHeight: 0, // 导航栏高度
        suggHeight: 0, // 建议列表高度 
        contentHeight: 0, // 可滚动内容区域高度
        searchContent: '', // 搜索关键词
        // 文章列表数据
        ArticleListPage: {
          reqStatus: '', // 请求状态
          dataStatus: 'loadmore', // 数据状态
          recommendList: [], // 文章精选推荐列表
          list: [], // 文章搜索结果列表
          page: 0
        },
        // 用户列表数据
        userListPage: {
          reqStatus: '', // 请求状态
          dataStatus: 'loadmore', // 数据状态
          recommendList: [], // 用户精选推荐列表
          list: [], // 用户搜索结果列表
          page: 0
        },
        historyListShow: true,
        historyEditStatus: false, //历史搜索编辑状态
        sourceHistoryList: [], // 历史搜索记录全部数据，默认展示的6个词条是从该数据中进行截取的
        showAllHistoryListState: false, // 是否展示全部历史搜索记录
        searchSuggeListShow: false, // 是否展示建议列表
        SearchSuggeList: [], // 搜索结果列表
        suggText: '', // 建议列表底部结束文本
        active: 0, // 选项卡激活索引
        // 选项卡列表数据 TODO
        navList: [{
            text: "文章",
          },
          {
            text: "用户",
          }
        ],
      };
    },
    onReady() {
      this.handleInit();
    },
    mounted() {},
    methods: {
      // 搜索页面数据初始化
      handleInit() {
        this.handleContentHeight();
        this.handleGetHistoryList();
        this.handleGetHotDisclos();
        this.handleGetHotUse();
      },
      //  通过导航栏组件返回的数据计算导航栏及建议列表区域高度
      handleNavLoad({
        height, // 子组件返回的可使用窗口高度
        navHeight // 子组件返回的导航栏高度
      }) {
        this.windowHeight = height;
        // 获取搜索页面导航栏高度
        this.navHeight = navHeight;
        // 获取建议列表区域高度
        this.suggHeight = height - navHeight;
      },
      // 获取推荐文章
      async handleGetHotDisclos() {
        let {
          data: res
        } = await getHotDiscloseApi();
        if (res.success) {
          this.ArticleListPage.recommendList = res.data.list
        }
      },
      // 获取推荐用户
      async handleGetHotUse() {
        let {
          data: res
        } = await getHotUseApi();
        if (res.success) {
          this.userListPage.recommendList = res.data.activeUser;
        }
      },
      // 跳转到文章详情页
      handleNavigateToArticleDetails(item) {
        console.log(item);
        uni.navigateTo({
          url: `/pages/community/article-details/article-details?id=${item.articleId}`,
        });
      },
      // 计算滚动区域的高度
      handleContentHeight() {
        // 因小程序平台兼容原因 采用节点方式获取指定元素信息  https://uniapp.dcloud.net.cn/api/ui/nodes-info.html#createselectorquery
        const query = uni.createSelectorQuery().in(this);
        query.select('.nav-container').boundingClientRect(data => {
          // 滚动区域的高度等于屏幕高度 - 导航栏高度 - 选项卡高度。
          this.contentHeight = this.windowHeight - this.navHeight - data.height;
        }).exec();
      },
      // ------------------------------------------------------------------------------- 历史记录
      // 删除历史记录
      handleRemoveHistory() {
        let arr = JSON.parse(uni.getStorageSync('kw'));
        if (arr.length <= 0) {
          uni.showModal({
            content: '暂无搜索历史',
          })
          return
        }
        this.historyEditStatus = !this.historyEditStatus;
      },

      // 更多历史记录
      handleLoadMoreHistory() {
        this.showAllHistoryListState = !this.showAllHistoryListState;
      },
      // 点击取消恢复默认
      historyCancel() {
        this.historyEditStatus = !this.historyEditStatus;
      },
      //点击删除历史或进行搜索
      handleHistoryClick(item) {
        if (this.historyEditStatus) {
          // 编辑状态下 点击标签 删除历史记录
          this.handleRemoveSingleHistory(item);
        } else {
          // 重置分页数据
          this.handlePageInit();
          // 非编辑状态下 点击历史记录 开始搜索
          this.handleSearch(item);
          this.historyListShow = false;
        }
      },
      // 保存搜索关键词的方法
      handleSaveSearchHistory(name) {
        // 利用set数据结构特性 元素不重复 https://es6.ruanyifeng.com/#docs/set-map
        const set = new Set(this.sourceHistoryList);
        // 先删除在添加 避免重复元素
        set.delete(name)
        this.sourceHistoryList = Array.from(set)
        this.sourceHistoryList.unshift(name);
        uni.setStorageSync('kw', JSON.stringify(this.sourceHistoryList))
      },
      // 清空历史记录
      handleCleanHistory() {
        uni.showModal({
          title: '提示',
          content: '是否清空历史记录',
          success: (res) => {
            if (res.confirm) {
              this.sourceHistoryList = []
              uni.setStorageSync('kw', '[]')
              this.historyEditStatus = false
            }
          }
        });

      },
      // 删除单个历史搜索记录
      handleRemoveSingleHistory(name) {
        uni.showModal({
          title: '提示',
          content: '是否清除当前历史记录',
          success: (res) => {
            if (res.confirm) {
              const set = new Set(this.sourceHistoryList)
              set.delete(name)
              this.sourceHistoryList = Array.from(set)
              uni.setStorageSync('kw', JSON.stringify(this.sourceHistoryList))
            }
          }
        });

      },
      // 在缓存中获取历史搜索记录，赋值给变量
      handleGetHistoryList() {
        this.sourceHistoryList = JSON.parse(uni.getStorageSync('kw') || '[]');
      },
      // 用设置用户关注状态
      handleUserFansState({
        id,
        fansState
      }, key) {
        const item = this.userListPage[key].find(item => item.userId == id)
        item.fansState = !fansState
        if (item.mutualConcern) {
          item.mutualConcern = false
        } else {
          item.mutualConcern = true
        }
      },
      // 获取搜索建议
      handleGetSearchSuggest(value) {
        if (!value.trim()) {
          // 搜索内容为空时 恢复默认状态
          this.handlePageInit()
          this.historyListShow = true;
          return;
        } else {
          this.historyListShow = false;
        }
        this.searchSuggeListShow = true;
        // 防抖
        clearTimeout(this.time)
        this.time = setTimeout(async () => {
          // this.active = 0;
          // 获取搜索建议列表

          let {
            data: res
          } = await getSearchSuggestApi(value.trim());
          if (res.success) {
            this.SearchSuggeList = res.data.list;
            this.suggText = '已全部加载';
          } else {
            this.suggText = '暂无搜索建议';
          }

        }, 300)

      },
      // 分页初始化
      handlePageInit() {
        this.ArticleListPage.list = [];
        this.userListPage.list = [];
        this.ArticleListPage.dataStatus = 'load-more';
        this.ArticleListPage.reqStatus = '';
        this.userListPage.dataStatus = 'load-more';
        this.userListPage.reqStatus = '';

        this.searchSuggeListShow = false
        this.historyEditStatus = false
        this.handleGetHistoryList()
      },
      // 搜索处理方法
      handleSearch(searchContent) {
        // 在搜索为空时，关闭搜索列表
        this.searchSuggeListShow = false;
        if (searchContent.trim() === '') {
          this.handlePageInit();
          return
        }
        // 处理搜索结果
        this.searchContent = searchContent.trim();
        this.handleLoadData(true);

      },
      // 加载数据
      async handleLoadData(init = false) {

        let apiFunc = getSearchDiscloseApi;
        let key = "";
        if (this.active === 0) {
          apiFunc = getSearchDiscloseApi;
          key = "ArticleListPage";
        } else {
          apiFunc = getSearchUserApi;
          key = "userListPage";
        }
        if (this[key].reqStatus) {
          return;
        }
        if (init) {
          this[key].page = 0;
        } else {
          if (this[key].dataStatus == 'no-more' || this[key].dataStatus == 'empty') {
            return;
          }
        }
        this[key].reqStatus = 'loading';
        let {
          data: res
        } = await apiFunc(this.searchContent, this[key].page + 1)
        if (res.success) {
          let _data = res.data.list.records;
          this[key].pages = res.data.list.pages;
          if (init) {
            // 首页加载 数据采用直接赋值方式，并且设置init为true，标识已加载过首页
            this[key].list = _data;
          } else {
            // 非首页加载 数据采用追加的方式
            this[key].list.push(..._data);
          }
          // 当前页数小于总页数 设置状态为done
          if (this[key].page < this[key].pages) {
            this[key].dataStatus = 'done';
          }
          // 当前页数大于等于总页数 设置状态为no-more
          if (this[key].page >= this[key].pages) {
            this[key].dataStatus = 'no-more';
          }
          // 首页加载时 获取的数据列表内容长度为0 则设置状态为empty
          if (init && this[key].list.length == 0) {
            this[key].dataStatus = 'empty';
          }
          this[key].page += 1
        }else{
           this[key].dataStatus = 'empty';
        }
        this[key].reqStatus = 'done';
        this.handleSaveSearchHistory(this.searchContent)
      },
      // 选项卡切换
      handleNavChange(index) {
        this.active = index;
        this.handlePageInit();
        this.handleSearch(this.searchContent)
      }
    },
    computed: {
      // 历史词条默认数量和全部数量的显示切换
      historyList() {
        if (this.showAllHistoryListState) {
          return this.sourceHistoryList;
        } else {
          return this.sourceHistoryList.slice(0, HISTORY_LIST_SHOW_NUM);
        }
      },
      // 用来控制历史词条更多图标显示与否的方法
      historyListMoreStatus() {
        return this.sourceHistoryList.length > HISTORY_LIST_SHOW_NUM;
      },
    }
  }
</script>
<style lang="scss" scoped>
  .search-details-page {
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    background-color: #eef2f4;

    // 搜索建议列表区域
    .sugg-list-container {
      background: #fff;
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      height: calc(100vh - 90rpx);
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.1);
      border-radius: 32rpx;
      z-index: 1;

      .sugg-item {
        font-size: 24rpx;
        padding: 26rpx;
        display: flex;
        align-items: center;
        border-bottom: 2rpx solid #EEF2F4;
        box-sizing: border-box;

        .sugg-item-text {
          margin-left: 28rpx;
          // 文字单行显示，使用 ... 代替溢出部分文字
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 6rpx;
        }
      }

      .sugg-tips {
        width: 100%;
        text-align: center;
        padding: 40rpx 0rpx;
        color: #AEAEAE;
        font-size: 24rpx;
        border-top: solid #EEF2F4 1px;
      }
    }

    // 历史搜索区域
    .history-container {
      width: 100%;
      padding: 36rpx 32rpx;
      box-sizing: border-box;

      .history-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 40rpx;

        .title {
          font-size: 28rpx;
        }


        .history-compile {
          font-size: 24rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          .history-empty {
            margin-right: 4rpx;
            color: #3FD3D1;
          }

          .history-cancel {
            margin-left: 4rpx;
          }
        }
      }

      .history-list-container {
        display: flex;
        flex-wrap: wrap;

        .history-item {
          min-width: 75rpx;
          max-width: 200rpx;
          height: 48rpx;
          line-height: 48rpx;
          text-align: center;
          border-radius: 30rpx;
          padding: 0 32rpx;
          background: #F5F5F5;
          position: relative;
          margin-top: 32rpx;
          margin-right: 16rpx;

          .text {
            font-size: 26rpx;
            color: #7A7A7A;
            display: -webkit-box;
            text-overflow: ellipsis;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
          }

          .remove-icon {
            position: absolute;
            top: 0;
            right: 0;
            transform: translateX(50%) translateY(-50%);
          }
        }

        .more-icon .icon {
          display: inline-block;
          transition: all 0.3s ease;
          transform: rotateZ(0deg);
        }

        .more-icon-expland .icon {
          transform: rotateZ(180deg);
        }

      }
    }

    .content-container {

      // 选项卡部分
      .nav-container {
        width: 400rpx;
        box-sizing: border-box;
      }

      .scroll-view-container {
        width: 100%;

        .recommend-container {
          padding: 0rpx 32rpx;
          box-sizing: border-box;
          width: 100%;
          height: 100%;

          .list-container {
            padding-top: 32rpx;
            box-sizing: border-box;



            .recommend-article {
              width: 100%;
              border-radius: 16px;
              background: url('@/static/bluebakcground.png') no-repeat;
              background-size: 100% 100%;
              display: flex;
              flex-direction: column;
              align-items: flex-end;
              padding: 48rpx 32rpx;
              box-sizing: border-box;



              .item {
                width: 100%;
                display: flex;
                align-items: center;
                position: relative;
                margin-bottom: 48rpx;

                .frame-item {
                  width: 32rpx;
                  height: 32rpx;
                  background: #cccccc;
                  color: #fff;
                  border-radius: 10rpx;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-shrink: 0;
                  font-size: 24rpx;
                }

                .text-item {
                  height: 100%;
                  font-size: 28rpx;
                  font-weight: 500;
                  letter-spacing: 1px;
                  color: #333333;
                  white-space: nowrap;
                  text-overflow: ellipsis;
                  overflow: hidden;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 1;
                  padding-left: 10rpx;
                }
              }

              .item:last-child {
                margin-bottom: 0rpx;
              }

              .item:first-child .frame-item {
                background: #EB4C39 !important;
              }

              .item:nth-child(2) .frame-item {
                background: #EE8041 !important;
              }

              .item:nth-child(3) .frame-item {
                background: #F2A748 !important;
              }

            }

            .item {
              margin-bottom: 48rpx;
            }
          }

        }


        // 用户列表区域
        .user-container {
          padding: 0rpx 32rpx;
          box-sizing: border-box;
          width: 100%;
          height: 100%;

          .list-container {
            padding: 32rpx 0;
            box-sizing: border-box;

            .item {
              background: #ffffff;
              width: 100%;
              padding: 32rpx;
              box-sizing: border-box;
              position: relative;

              // 用户卡片分隔线
              &::after {
                position: absolute;
                width: calc(100% - 64rpx);
                left: 32rpx;
                bottom: 0rpx;
                height: 1px;
                background: #EEF2F4;
                content: "";
              }
            }

            .item:first-child {
              border-radius: 20px 20px 0px 0px;
            }

            .item:last-child {
              border-radius: 0px 0px 20px 20px;

              &::after {
                display: none;
              }
            }

            .item-one {
              border-radius: 20px !important;
            }

            .recommend-user {
              background: white;
              border-radius: 20px;
            }
          }

        }

      }

      .list-status-container {
        width: 100%;
        text-align: center;
        padding: 40rpx 0rpx;
        color: #AEAEAE;
        font-size: 24rpx;
        border-top: solid #EEF2F4 1px;
      }

    }

  }
</style>